import axios, { type AxiosResponse } from "axios";

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: parseInt(import.meta.env.VITE_API_TIMEOUT || "5000"),
  headers: {
    "Content-Type": "application/json",
  },
});
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      //   config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code !== 200) {
      console.error("业务错误:", response.data.message);
      return Promise.reject(response.data);
    }
    return response; // 确保返回响应对象
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.error("未授权，请重新登录");
          break;
        case 403:
          console.error("拒绝访问");
          break;
        case 404:
          console.error("请求资源不存在");
          break;
        case 500:
          console.error("服务器错误");
          break;
        default:
          console.error("未知错误");
      }
    }
    return Promise.reject(error);
  }
);
// 定义基础响应类型
export interface BaseResponse<T = any> {
  code: number;
  message: string;
  data: T;
}
// 封装GET方法
export function get<T>(url: string, params?: any): Promise<BaseResponse<T>> {
  return instance.get(url, params);
}

// 封装POST方法
export function post<T>(url: string, data?: any): Promise<BaseResponse<T>> {
  return instance.post(url, data);
}
